package com.jgzx.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author jackesy
 * @className: JwtUtil
 * @description: JWT工具类
 * @create 2019/11/7 18:51
 **/
@Slf4j
public class JwtUtil {

    public static final String SECRET = "@jgzx!2021.04.01#@";

    /**
     * 生成token
     * @param user_id 用户id
     * @return
     */
    public static String createToken(Long user_id){
        Date now = DateUtil.offsetSecond(new Date(), -300);
        // header Map
        Map<String, Object> map = new HashMap<>();
        map.put("alg", "HS256");
        map.put("typ", "JWT");
        // build token
        // param backups {iss:Service, time:System.currentTimeMillis()}
        String token = JWT.create().withHeader(map) // header
                .withClaim("iss", "Service") // payload
                .withClaim("time", System.currentTimeMillis()) // payload
                .withClaim("user_id", null == user_id ? null : user_id.toString())
                .withIssuedAt(now) // sign time
                .sign(Algorithm.HMAC256(SECRET)); // signature
        return token;
    }

    /**
     * 解密Token
     * @param token
     * @return
     * @throws Exception
     */
    private static Map<String, Claim> verifyToken(String token) throws JWTVerificationException {
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
        DecodedJWT jwt = verifier.verify(token);
        return jwt.getClaims();
    }

    /**
     * 根据Token获取user_id
     * @param token
     * @return user_id
     */
    public static Long getUserId(String token){
        Map<String, Claim> claims = null;
        try {
            claims = verifyToken(token);
        } catch (JWTVerificationException e){
            log.error("token无效:" + e.getMessage());
            e.printStackTrace();
            return null;
        }
        Claim user_id_claim = claims.get("user_id");
        if (null == user_id_claim || StrUtil.isEmpty(user_id_claim.asString())) {
            return null;
        }
        return Long.valueOf(user_id_claim.asString());
    }

}
